package com.woniuxy.purchasemanager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.commons.entity.purchaseManager.PurchaseOrderEntity;
import com.woniuxy.purchasemanager.service.PurchaseOrderFileService;
import com.woniuxy.purchasemanager.service.PurchaseOrderService;
import com.woniuxy.purchasemanager.util.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName PurchaseOrderServiceImpl
 * @Description 采购单导出实现类
 * @Author xianhao
 * @Date 2022/4/20 10:52
 * @Version 1.0.0
 */
@Service
public class PurchaseOrderFileServiceImpl implements PurchaseOrderFileService {

    private final static Logger LOGGER = LoggerFactory.getLogger(PurchaseOrderFileServiceImpl.class);

    //获取单元格样式
    HorizontalCellStyleStrategy cellStyleStrategy = ExcelUtils.getHorizontalCellStyleStrategy();

    private static final String filename = "采购单导出数据表";

    @Resource
    private PurchaseOrderService purchaseOrderService;

    @Override
    public void exportDataToExcel(HttpServletResponse response) {

        ExcelWriter excelWriter = null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(filename + "-" + System.currentTimeMillis(), "UTF-8")
                    .replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里 需要指定写用哪个class去写
            excelWriter = EasyExcel.write(response.getOutputStream(), PurchaseOrderEntity.class).build();
            // 这里注意 如果同一个sheet只要创建一次
            WriteSheet writeSheet = EasyExcel.writerSheet("").registerWriteHandler(cellStyleStrategy).build();
            // 去调用写入,实际使用时根据数据库分页的总的页数来
            writeSheet.setSheetName("sheet" + 1);
            // 去数据库查询每一页的数据
            excelWriter.write(getPurchaseOrderData(), writeSheet);
            LOGGER.info("数据导出完成");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出数据失败！错误信息为：{}", e.getMessage());
        } finally {
            //千万别忘了finish,会帮我们自动关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 获取采购单导出数据
     *
     * @return list
     */
    public List<PurchaseOrderEntity> getPurchaseOrderData() {
        //查询数据
        List<PurchaseOrderEntity> result = purchaseOrderService.list(new QueryWrapper<>());
        //判空
        if (CollectionUtils.isEmpty(result)) {
            LOGGER.error("查询数据为null");
        }
        return result;
    }

}
